package com.app.milkteaapp.fragment;


import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.app.milkteaapp.R;
import com.app.milkteaapp.adapter.CartAdapter;
import com.app.milkteaapp.bean.Cart;
import com.app.milkteaapp.bean.FindCartGsonBean;
import com.app.milkteaapp.bean.FindMilkTeaGsonBean;
import com.app.milkteaapp.bean.FindOrderGsonBean;
import com.app.milkteaapp.bean.FindUserGsonBean;
import com.app.milkteaapp.bean.LoginGsonBean;
import com.app.milkteaapp.bean.RechargeGsonBean;
import com.app.milkteaapp.bean.RegisterGsonBean;
import com.app.milkteaapp.utils.GsonUtils;
import com.app.milkteaapp.utils.MyTools;
import com.app.milkteaapp.utils.OkHttpUtils;
import com.app.milkteaapp.utils.SpUtils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class ShopCartFragment extends Fragment {
    private static final String TAG = "ShopCartFragment";

    private ListView listView;
    private TextView tvPrice;
    private TextView tvBuy;
    private LoginGsonBean.User user;
    private Float needPay;

    //carts是用于显示adapter的list
    public List<Cart> carts;

    //cartList是在数据库中查询到cart的列表
    public List<FindCartGsonBean.Cart> cartList;


    public ShopCartFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_shop_cart, container, false);
        init(view);
        user = SpUtils.getUserBean(getContext());
        //Log.d(TAG, "onCreateView: user:"+user.toString());
        sendRequest();
        return view;
    }

    public void init(View view) {
        listView = view.findViewById(R.id.list_cart);
        tvPrice = view.findViewById(R.id.tv_price_cart);
        tvBuy = view.findViewById(R.id.tv_buy_cart);
        tvBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buy();
            }
        });
    }

    //发送查询购物车的请求
    public void sendRequest() {
        carts = new ArrayList<>();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("id", user.getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Log.d(TAG, "sendRequest: "+jsonObject.toString());
        Call call = OkHttpUtils.MyCall(MyTools.URL + "/cart/findByUserId", jsonObject.toString());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d(TAG, "onFailure: " + e);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(), "网络炸了", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                FindCartGsonBean findCartGsonBean = GsonUtils.fromJson(string, FindCartGsonBean.class);

                //当查询到购物车时
                if (findCartGsonBean.isSuccess()) {
                    //若购物车为空
                    if (findCartGsonBean.getData().isEmpty()) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getContext(), "购物车是空的哦~", Toast.LENGTH_SHORT).show();
                                updateUi();
                            }
                        });
                        //若不为空，则通过for循环遍历查询订单
                    } else {
                        cartList = findCartGsonBean.getData();
                        for (int i = 0; i < cartList.size(); i++) {
                            findOrder(cartList.get(i).getOrderid(),i);
                        }
                    }
                }
            }
        });
    }

    //发送查询订单的请求
    private void findOrder(Integer id, final int i) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("id", id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Call call = OkHttpUtils.MyCall(MyTools.URL + "/order/findById", jsonObject.toString());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d(TAG, "onFailure: " + e);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(), "网络炸了", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                FindOrderGsonBean findOrderGsonBean = GsonUtils.fromJson(string, FindOrderGsonBean.class);

                FindOrderGsonBean.Order order = findOrderGsonBean.getData();
                //Log.d(TAG, "onResponse: "+findOrderGsonBean.toString());

                if (findOrderGsonBean.isSuccess()) {
                    if (order == null) {
                        Log.d(TAG, "onResponse: 空订单");

                    } else {
                        findMilkTea(order.getTeaid(),i);
                    }
                }
            }
        });
    }

    //发送查询奶茶的请求
    private void findMilkTea(Integer id,int i) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("id", id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Call call = OkHttpUtils.MyCall(MyTools.URL + "/milkTea/findById", jsonObject.toString());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d(TAG, "onFailure: " + e);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(), "网络炸了", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                FindMilkTeaGsonBean findMilkTeaGsonBean = GsonUtils.fromJson(string, FindMilkTeaGsonBean.class);

                if (findMilkTeaGsonBean.isSuccess()) {
                    FindMilkTeaGsonBean.MilkTea milkTea = findMilkTeaGsonBean.getData();
                    Cart cart = new Cart(milkTea.getImg(), milkTea.getName(), milkTea.getPrice());
                    carts.add(cart);
                    updateUi();
                }
            }
        });
    }

    //更新界面
    private void updateUi() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                int price = 0;
                for (int i = 0; i < carts.size(); i++) {
                    Integer thisPrice = carts.get(i).getPrice();
                    price += thisPrice;
                }
                needPay = Float.valueOf(price);
                tvPrice.setText(price + "元");
                listView.setAdapter(new CartAdapter(getActivity(), carts,ShopCartFragment.this));
            }
        });
    }

    //点击购买按钮时
    public void buy() {
        //先查询user
        final JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("id", user.getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Call call = OkHttpUtils.MyCall(MyTools.URL + "/user/findById", jsonObject.toString());

        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d(TAG, "onFailure: " + e);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(), "网络炸了", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                FindUserGsonBean findUserGsonBean = GsonUtils.fromJson(string, FindUserGsonBean.class);

                Log.d(TAG, "onResponse: 查到余额"+findUserGsonBean.getData().getMoney());

                //当查询成功时
                if (findUserGsonBean.isSuccess()) {
                    if (findUserGsonBean.getData().getMoney() >= needPay) {
                        //如果用户能够承担费用，则进行购买并更新用户余额
                        buy2(findUserGsonBean.getData().getMoney(),cartList);
                    } else {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), "余额不足~请先充值~", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }
        });
    }

    private void buy2(Float money, final List<FindCartGsonBean.Cart> cartList) {
        Float newMoney = money - needPay;
        JSONObject jsonObject1 = new JSONObject();

        try {
            jsonObject1.put("money", newMoney);
            jsonObject1.put("id", user.getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Call call1 = OkHttpUtils.MyCall(MyTools.URL + "/user/recharge",jsonObject1.toString());

        call1.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d(TAG, "onFailure: " + e);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(), "网络炸了", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string1 = response.body().string();
                RechargeGsonBean rechargeGsonBean = GsonUtils.fromJson(string1, RechargeGsonBean.class);

                Log.d(TAG, "onResponse: "+rechargeGsonBean);

                if (rechargeGsonBean.isSuccess()) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            for (int i = 0; i < cartList.size(); i++) {
                                deleteCart(cartList.get(i));
                                updateUi();
                            }
                            Toast.makeText(getContext(), "购买成功！", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    //删除购物车中的项目
    public void deleteCart(FindCartGsonBean.Cart cart) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("id", cart.getId());
            jsonObject.put("orderid", cart.getOrderid());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Call call = OkHttpUtils.MyCall(MyTools.URL + "/cart/delete", jsonObject.toString());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d(TAG, "onFailure: " + e);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(), "网络炸了", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                RegisterGsonBean gsonBean = GsonUtils.fromJson(string, RegisterGsonBean.class);
                if (gsonBean.isSuccess()) {
                   sendRequest();
                }
            }
        });
    }
}
